import axios from 'axios';
import 'element-plus/es/components/message/style/css'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/userStore';
import router from '@/router'
const httpInstance = axios.create({//创建基地址实例,
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000,
})

//拦截器
//axios 请求拦截器
httpInstance.interceptors.request.use (config => {
  //从pinia获取token
const userStore = useUserStore()
const token = userStore.userInfo.token
if(token){
  config.headers.Authorization = `Bearer ${token}`
}
return config
}, e => Promise.reject (e))

//axios 响应式拦截器
httpInstance.interceptors.response.use (res => res.data, e => {
  const userStore = useUserStore()
ElMessage({
  type:'warning',
  message:e.response.data.message
})
//token校验失败,就是太久时间没管页面，token校验失败，要清除数据，并重新回到登录页登录
if(e.response.status === 401){
  userStore.clearUserInfo()//先清除数据
  router.push('/login')
}
return Promise.reject (e)
})

export default httpInstance;
